import { defineStore } from "pinia"
import { getAxios } from "/axios"
const waitList = {}
const zeroDict = {}
export const useDictStore = defineStore("dict", {
	state() {
		return {
			dict: {},
		}
	},
	actions: {
		// 枚举  字典
		getDict(url, reload) {
			if (!reload && this.hasDict(url)) {
				if (this.dict[url].length !== 0 || zeroDict[url]) {
					return Promise.resolve(this.dict[url])
				} else {
					return new Promise((resolve, reject) => {
						waitList[url] ??= []
						waitList[url].push({ resolve, reject })
					})
				}
			} else {
				this.dict[url] = []
			}
			return new Promise(async (resolve, reject) => {
				try {
					const result = await getAxios(url)
					if (result.length === 0) {
						zeroDict[url] = true
					}
					this.dict[url] = result
					resolve(result)
					if (waitList[url]?.length) {
						waitList[url].forEach(item => item.resolve(result))
						delete waitList[url]
					}
				} catch (error) {
					reject(error)
					if (waitList[url]?.length) {
						waitList[url].forEach(item => item.reject(error))
						delete waitList[url]
					}
					delete this.dict[url]
				}
			})
		},
		async getDictValue(name, code, options = {}) {
			options.label = options.label || "name"
			options.value = options.value || "code"
			let dict = name
			if (typeof name === "string") {
				await this.getDict(name)
				dict = this.dict[name]
			}
			return Promise.resolve(dict.find(item => item[options.value] == code)?.[options.label])
		},
		getDictValues(name, codes, options = {}) {
			if (!Array.isArray(codes)) {
				if (codes === null || codes === undefined || codes === "") {
					return Promise.resolve([])
				}
				codes = [codes]
			}
			const promiseArray = []
			codes.forEach(code => {
				promiseArray.push(this.getDictValue(name, code, options))
			})
			return Promise.all(promiseArray)
		},
		hasDict(name) {
			return !!this.dict[name]
		},
	},
	getters: {},
})
